package com.lh.microservice2.controller;

import com.lh.microservice2.common.constant.MicroServiceConstant;
import com.lh.microservice2.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * @author lh
 * @Description:
 * @date 2021/3/26 9:47
 */
@RestController
@RequestMapping("/Person")
public class PersonController {
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private DiscoveryClient discoveryClient;

	/**
	 * TODO 主要练习单纯使用eureka
	 * 从传统的restTemplate调用固定url的写法
	 * 升级为
	 * 可以通过注册服务名获取服务实例，通过服务实例动态获取ip和端口
	 * 好处：
	 * 服务提供方部署环境发生变化，服务调用方减少修改大量url的工作
	 *
	 * @return
	 */
	@GetMapping("/findPersonAndDeal")
	public Person findPersonAndDeal() {
		List<ServiceInstance> instances = discoveryClient.getInstances(MicroServiceConstant.MICROSERVICE1_NAME);
		/**
		 * 练习阶段只启动了一个microService1，所以直接取第一个就可以了。
		 */
		ServiceInstance instance = instances.get(0);
		Person[] personArray = restTemplate.getForObject("http://" + instance.getHost() + ":" + instance.getPort() + "/person/getAllPerson", Person[].class);
		List<Person> personList = Arrays.asList(personArray);
		Person person = null;
		for (Person person1 : personList) {
			if ("lh".equals(person1.getName())) {
				person = person1;
			}
		}
		return person;
	}

}
